import http from '../../utils/http'
import { isLogin, toLogin, getUserInfo, clearCacheAll } from '../../utils/auth'

Page({

    /**
     * 页面的初始数据
     */
    data: {
        addressList: [],
        hasAddress: true,
        defaultAddress: null,

        // 0：表示从“地址管理”进入
        // 1：表示从“去结算”页面进入
        type: 0,

        userInfo: null,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({type: options.type})
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // 用户登录信息
        this.setData({ userInfo: getUserInfo() });

        this.getAddressLists()
    },

    /**
     * 获取会员地址列表
     */
    async getAddressLists() {
        let { userInfo } = this.data
        let res = await http.get('/api/mall/umsmemberreceiveaddress/list', {memberId: userInfo.id})
        if(res.status) {
            if(res.data) {
                let list = res.data
                // 默认地址
                let isDefault = list.filter(item => item.isDefault == true)
                this.setData({ addressList: list, defaultAddress: isDefault.length > 0? isDefault[0].id : null })
            }
        }
    },

    /**
     * 修改默认地址
     * @param {*} e 
     */
    async onChangeDefaultAddress(e) {
        const id = e.detail
        let { userInfo } = this.data
        let res = await http.get('/api/mall/umsmemberreceiveaddress/changeDefault', {id, memberId: userInfo.id})
        if(res.status) {
            this.getAddressLists()
        }
    },

    /**
     * 选择地址，返回
     * @param {*} e 
     */
    onChangeSelectAddress(e) {
        const { address } = e.currentTarget.dataset
        if(this.data.type == 1) {
            wx.setStorageSync('address', address);
            wx.navigateBack({ delta: 1 });
        }
    },

    /**
     * 新增地址
     * @param {*} e 
     */
    addAddress(e) {
        wx.navigateTo({ url: '/pages/user_address_edit/user_address_edit' });
    },

    /**
     * 编辑地址
     * @param {*} e 
     */
    editAddress(e) {
        const { item } = e.currentTarget.dataset
        wx.navigateTo({ url: `/pages/user_address_edit/user_address_edit?type=edit&data=${JSON.stringify(item)}`});
    },

    /**
     * 删除地址
     * @param {*} e 
     */
    async deleteAddress(e) {
        const { id } = e.currentTarget.dataset
        let res = await http.post('/api/mall/umsmemberreceiveaddress/delete', [id])
        if(res.status) {
            this.getAddressLists()
        }
    }


})